//
//  MANetwork.m
//  meiang_edu
//
//  Created by 李国栋 on 2018/10/19.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MANetwork.h"
#import "AFNetworking.h"
#import "MaTool.h"
@interface MANetwork()
@property (nonatomic ,strong) AFHTTPSessionManager *afManager;
@end

@implementation MANetwork
+ (void)POST:(NSString *)URLString parameters:(nullable NSDictionary *)parameters autoShowFailAlert:(BOOL)autoAlert showLoading:(BOOL)showLoading success:(MASuccessBlock)success failure:(MAFailBlock)failure{
    [self POSTString:URLString bodyString:parameters.mj_JSONString autoShowFailAlert:autoAlert showLoading:showLoading success:success failure:failure];
}

+ (void)POSTString:(NSString *)URLString bodyString:(nullable NSString *)bodyString autoShowFailAlert:(BOOL)autoAlert showLoading:(BOOL)showLoading success:(MASuccessBlock)success failure:(MAFailBlock)failure{
    if (showLoading) {
        [MBManager showLoading];
    }
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    AFHTTPSessionManager *afManager = [MANetwork shareInstance].afManager;
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:nil error:nil];
    [req setValue:@"application/text" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [req setValue:userinfo.token forHTTPHeaderField:@"token"];
    if (bodyString) {
        [req setHTTPBody:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    [[afManager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [MBManager hideAlert];
        if (!error) {
            NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if (responseDic) {
                NSNumber * errorcode = responseDic[@"msgcode"];
                
                if ([errorcode integerValue] != 1) {
                    NSString * errorString = responseDic[@"message"];
                    
                    if ([MaTool isEmptyStr:errorString]) {
                        errorString = @"执行失败";
                    }
                    [MBManager showBriefAlert:errorString];
                    
                    
                }
                success(responseDic,([errorcode integerValue] == 1));
                
            }else{
                
                success(@{@"responseObject":responseObject},NO);
            }
        } else {
            failure(error);
            [MBManager showBriefAlert:@"请求失败,请检查网络设置"];
        }
    }] resume];
}

+ (void)GET:(NSString *)URLString parameters:(nullable NSDictionary *)parameters autoShowFailAlert:(BOOL)autoAlert showLoading:(BOOL)showLoading success:(MASuccessBlock)success failure:(MAFailBlock)failure{
    AFHTTPSessionManager *afManager = [MANetwork shareInstance].afManager;
    if (showLoading) {
        [MBManager showLoading];
    }
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [afManager.requestSerializer setValue:userinfo.token forHTTPHeaderField:@"token"];
    URLString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)URLString, NULL, NULL, kCFStringEncodingUTF8));
    // GET
    [afManager GET:URLString
         parameters:parameters
           progress:^(NSProgress * _Nonnull downloadProgress) {
           } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
               [MBManager hideAlert];
               NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
               if (responseDic) {
                   NSNumber * errorcode = responseDic[@"msgcode"];
                   
                   if ([errorcode integerValue] != 1) {
                       NSString * errorString = responseDic[@"message"];
                       
                       if ([MaTool isEmptyStr:errorString]) {
                           errorString = @"执行失败";
                       }
                       if (autoAlert) {
                           [MBManager showBriefAlert:errorString];
                       }
                       
                       
                   }
                   success(responseDic,([errorcode integerValue] == 1));
                   
               }else{
                   
                   success(@{@"responseObject":responseObject},NO);
                   
               }
               
           } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
               failure(error);
               [MBManager hideAlert];
               [MBManager showBriefAlert:@"请求失败,请检查网络设置"];
           }];
}

+(instancetype)shareInstance{
    static MANetwork * network = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        network = [MANetwork new];
    });
    return network;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initManager];
    }
    return self;
}

- (void)initManager{
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    AFHTTPSessionManager *afManager = [AFHTTPSessionManager manager];
    [afManager.requestSerializer setValue:@"application/text" forHTTPHeaderField:@"Content-Type"];
    [afManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [afManager.requestSerializer setValue:userinfo.token forHTTPHeaderField:@"token"];
    afManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    _afManager = afManager;
}

@end
